package com.xudow.app.wxapi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.OrderPayments;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.OrderStudentSelectActivity;
import com.xudow.app.ui.PayStatusPopup;
import com.xudow.app.ui.task.PaymentUpdateTask;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.util.Maps;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler,DialogInterface.OnClickListener{
    private static final String TAG = makeLogTag(WXPayEntryActivity.class);

    private IWXAPI api;

    private PaymentUpdateTask paymentUpdateTask;

    private PayStatusPopup popup;
    RelativeLayout root;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wx_pay_result);
        root =(RelativeLayout) findViewById(R.id.root);
        api = WXAPIFactory.createWXAPI(this, Config.WX_APPID);

        if (null != getIntent()) {
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (0 == resp.errCode) {
                //如果是支付成功，首先修改支付信息
                XApplication application = (XApplication) getApplication();

                OrderPayments payment = application.currentOrderPayments;

                HashMap<String, String> params = Maps.newHashMap();
                params.put("payment_id", "" + payment.getId());
                params.put("pay_status", "1"); //0：支付失败 1：支付成功 2:等待支付结果

                application.currentOrderPayments = null;

                paymentUpdateTask = new PaymentUpdateTask(WXPayEntryActivity.this, paymentUpdateTaskHandler);
                paymentUpdateTask.execute(params);
            } else {
                //支付失败

                String message = getString(R.string.pay_result_fail_tip);

               // View root = findViewById(R.id.root);

                try {
                    popup = new PayStatusPopup(WXPayEntryActivity.this, R.mipmap.ico_cry_face, message);
                    popup.showAtLocation(root, Gravity.CENTER, 0, 0);
                } catch (Exception e) {
                    LOGE(TAG, e.getMessage(), e);

                    finish();

                    return;
                }

                gotoMyOrdersHandler.sendEmptyMessageDelayed(1, 3000);
            }
        }

    }

    /**
     * 更新支付信息Handler
     */
    private Handler paymentUpdateTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (PaymentUpdateTask.SUCCESS == msg.what) {
                String message = "支付成功";
                int iconRes = R.mipmap.icon_green_check;

                popup = new PayStatusPopup(WXPayEntryActivity.this, iconRes, message);
                popup.showAtLocation(findViewById(R.id.root), Gravity.CENTER, 0, 0);

                //3秒钟后弹窗消失，转到填已支付订单详情
                gotoMyOrdersHandler.sendEmptyMessageDelayed(0, 3000);
            }
        }
    };

    /**
     * 跳转到支付订单列表
     */
    private Handler gotoMyOrdersHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            XApplication application = (XApplication) getApplication();

            if (null != popup) {
                popup.dismiss();
                popup = null;
            }

            if (msg.what <= 0) {
               /* application.closeChainActivities();

                long currentOrderId = application.currentOrderId;

                Intent intent = new Intent(WXPayEntryActivity.this, OrderStudentSelectActivity.class);
                intent.putExtra("orderId", currentOrderId);
                startActivity(intent);

                application.currentOrderId = null;

                finish();*/
                dialog("是否现在为学生选座");
            }
        }
    };

    /**
     * 对话框
     */
    protected void dialog(String title) {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage(title);  builder.setTitle("提示");
        builder.setPositiveButton("确认",WXPayEntryActivity.this);
        builder.setNegativeButton("取消", WXPayEntryActivity.this);
        builder.create().show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (-1==which){
            //TODO 跳转到已支付订单列表
            Intent intent = new Intent(getApplicationContext(), OrdersActivity.class);
            intent.putExtra("orderstate",0);
            startActivity(intent);

        }
        dialog.dismiss();
        finish();
    }
}